<template>
  <div class="chart-container" :style="style">
    <!-- 准备一个有宽高的dom ———— 其他内容从父组件传过来 -->
    <div :id="uid" ref="chartDom" :style="style"></div>
  </div>
</template>
<script setup>
import { ref, computed, watch, onMounted, markRaw} from 'vue'
import * as echarts from 'echarts';
const props =  defineProps({
    dataSource: {
        type: Object,
        default: null,
        required: true
    },
    chartWidth: {
        type: String,
        default: '',
        required: true
    },
    chartHeight: {
        type: String,
        default: '',
        required: true
    }
})
const chartDom = ref(null)
const myChart = ref(null)
const uid = ref('')
uid.value = new Date().getTime() + Math.random().toString(32).slice(2, 10)
 
let style = computed(() => ({
    width: props.chartWidth,
    height: props.chartHeight
}))
 
const init = () => {
    // 基于准备好的dom,初始化echarts实例
    myChart.value = markRaw(echarts.init(chartDom.value, 'dark'))
    // 绘制图表
    myChart.value.setOption(props.dataSource)
}

onMounted(() => {
  init()
  window.addEventListener('resize', () => {
    if(myChart.value) {
      myChart.value.resize()
    }
  }, false)
})
 
watch(() => props.dataSource, (newVal, oldVal) => {
  if(myChart.value) {
    myChart.value.setOption(newVal)
  }
}, {deep: true})
 
</script>
<style lang="scss" scoped>
.chart-container {
  height: 100%;
  width: 100%;
  border-radius: 4px;
  box-shadow:  5px 5px 10px #7b7b7b;
}
</style>